<template>
  <view class="top">
    <view class="self">
      <text class="phone">12341234123</text>
      <text class="local">广东省 湛江市 麻章区 瑞康二横路37号</text>
      <text class="time">营业时间：09:00-21:00</text>
    </view>

    <view class="borders">
      <view class="blue"></view>
      <view class="pink"></view>
      <view class="blue"></view>
      <view class="pink"></view>
      <view class="blue"></view>
      <view class="pink"></view>
      <view class="blue"></view>
      <view class="pink"></view>
      <view class="blue"></view>
      <view class="pink"></view>
      <view class="blue"></view>
      <view class="pink"></view>
    </view>
  </view>

  <!-- 下单的甜品信息 -->
  <view class="desserts">
    <view class="item">
      <up-image
        :src="`http://localhost:8080/api/files/${diyList.dessertImg}`"
        width="140rpx"
        height="140rpx"></up-image>
      <text class="name">{{ diyList.dessertName }}</text>
      <text class="specs">{{ diyList.specs }}</text>
      <text class="price">{{ '￥' + diyList.dessertPrice }}</text>
    </view>
  </view>

  <!-- 信息填写框 -->
  <view class="info">
    <!-- 上门时间 -->
    <view class="time" @click="openPop">
      <text>预约时间</text>
      <view class="right">
        <text class="timeText">{{ pickTime }}</text>
        <text class="jiantou">&gt;</text>
      </view>
    </view>

    <!-- // 自提联系方式 -->
    <view class="name">
      <text>联系人</text>
      <input
        type="text"
        placeholder="请输入联系人姓名"
        v-model="orderList.username" />
    </view>

    <view class="phone">
      <text>联系手机号</text>
      <input
        type="text"
        placeholder="请输入联系人手机号"
        v-model="orderList.phone" />
    </view>

    <!-- 买家留言 -->
    <view class="msg">
      <text>买家留言</text>
      <input
        type="text"
        placeholder="请输入留言信息"
        v-model="orderList.message" />
    </view>
  </view>

  <!-- 优惠劵 -->
  <view class="coupons">
    <text>优惠劵</text>
    <view class="selcou" @click="couponShow = true">
      <text class="couname" v-if="Object.keys(coupon).length > 0">
        {{ coupon.money }}元通用优惠劵
      </text>
      <text class="jiantou">&gt;</text>
    </view>
  </view>

  <up-picker
    :show="couponShow"
    :columns="couponColumn"
    keyName="label"
    @cancel="couponShow = false"
    @confirm="confirmCoupon"></up-picker>

  <!-- 金额 -->
  <view class="money">
    <view class="count">
      <text class="zi">金额总计</text>
      <text class="price">{{ '￥' + diyList.dessertPrice }}</text>
    </view>
    <view class="cou">
      <text class="zi">优惠劵</text>
      <text class="subs">-￥{{ coupon.money }}</text>
    </view>
  </view>

  <!-- 底部订单提交 -->
  <view class="footer">
    <view class="left">
      合计:
      <text class="money">{{ '￥' + price }}</text>
    </view>
    <view class="right" @click="confirmBook">提交订单</view>
  </view>
  <DatePicker ref="datePicker" @update-getTime="getTime" />
</template>

<script setup>
import { onLoad, onShow } from '@dcloudio/uni-app'
import { ref, nextTick } from 'vue'
import { addOrderService, addOrderDetailService } from '@/api/order.js'
import { useUserStore } from '@/stores/user.js'
import {
  updateCoupon,
  delUserCoupon,
  getCouponService,
  getCouponDetail,
} from '@/api/coupons.js'
import DatePicker from '@/components/DatePicker/DatePicker.vue'

const userStore = useUserStore()
const datePicker = ref(null)

const orderList = ref({
  userId: userStore.userInfo.userId,
  amount: 0,
  username: '',
  phone: '',
  address: '',
  time: '',
  delivery: '',
  message: '',
  type: 'diy',
  status: 1,
})

// 优惠劵
const couponShow = ref(false)
let couponList = ref([])
let couponColumn = ref([])

const diyList = ref({})
// 计算价格
const price = ref(0)
onLoad((option) => {
  if (option.diyDessert) {
    diyList.value = JSON.parse(decodeURIComponent(option.diyDessert))
  }
  price.value = diyList.value.dessertPrice
  nextTick(() => {
    datePicker.value.getNextDay()
  })
})

onShow(async () => {
  couponColumn.value = []
  const res = await getCouponService(userStore.userInfo.userId)

  if (res.code == 0) {
    couponList.value = res.data ?? []
    // 构造数据添加到选择器中
    if (couponList.value.length > 0) {
      let column = ref([])
      couponList.value.map(async (item) => {
        // 根据优惠劵ID获取优惠劵详情信息
        const result = await getCouponDetail(item.couponsId)
        if (result.code == 0) {
          column.value.push({
            label: `通用优惠劵${result.data.money}元`,
            couponId: item.id,
            money: result.data.money,
            id: result.data.id,
            count: item.count,
          })
        }
      })
      couponColumn.value.push(column.value)
    }
  } else {
    couponColumn.value = []
  }
})

// 选择时间
// 打开时间选择器
const openPop = () => {
  datePicker.value.showBox()
}

const pickTime = ref('')
const getTime = (value) => {
  pickTime.value = value || ''
}

// 确认选择优惠劵
const coupon = ref({})
const confirmCoupon = (e) => {
  coupon.value = {}
  couponShow.value = false
  const { value } = e
  coupon.value = {
    ...value[0],
  }
  if (Object.getOwnPropertyNames(coupon.value).length > 0) {
    price.value = (
      parseFloat(price.value) - parseInt(coupon.value.money)
    ).toFixed(2)
  }
}

const dessertList = ref({
  orderId: 0,
  dessertId: '',
  num: 1,
  total: 0,
})

// 提交订单
const details = ref([])
const confirmBook = async () => {
  orderList.value.amount = price.value
  orderList.value.time = pickTime.value
  orderList.value.status = 4 // 待完成订单状态
  const res = await addOrderService(orderList.value)
  if (res.code == '0') {
    // 添加订单详情
    orderList.value.time = ''
    // 详情数据
    dessertList.value.orderId = res.data.id
    dessertList.value.dessertId = diyList.value.id
    dessertList.value.total = diyList.value.dessertPrice

    details.value.push(dessertList.value)

    const detail = await addOrderDetailService(details.value)

    if (detail.code === '0') {
      // 当用户为普通用户时 如果总额大于30更新用户的身份为会员
      if (userStore.userInfo.member === 1) {
        if (parseFloat(orderList.value.amount) >= 30) {
          userStore.updateMember(2)
        }
      }

      // 更新用户的积分
      if (userStore.userInfo.member === 2) {
        const point =
          userStore.userInfo.points +
          Math.floor(parseInt(orderList.value.amount) / 2)
        userStore.updatePoint(point)
      }

      // 修改优惠劵数量
      if (Object.getOwnPropertyNames(coupon.value).length > 0) {
        // 优惠劵数量减一
        coupon.value.count -= 1
        if (coupon.value.count <= 0) {
          // 删除表信息
          await delUserCoupon(coupon.value.couponId)
        } else {
          // 修改优惠劵数量
          const userCoupon = {
            id: coupon.value.couponId,
            userId: userStore.userInfo.userId,
            couponsId: coupon.value.id,
            count: coupon.value.count,
          }
          await updateCoupon(userCoupon)
        }
      }

      // 跳转到我的订单页
      uni.showToast({
        title: '创建订单成功',
        icon: 'none',
      })

      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/myDiyOrder/myDiyOrder',
        })
      }, 1500)
    } else {
      uni.showToast({
        title: '创建订单失败',
        icon: 'none',
      })
    }
  } else {
    uni.showToast({
      title: res.message,
      icon: 'none',
    })
    order.value.time = time
  }
}
</script>

<style lang="scss" scoped>
.top {
  width: 95%;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 10rpx;
  font-size: 38rpx;

  .self {
    width: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
    padding: 10rpx;
    .phone {
      font-size: 32rpx;
      font-weight: bold;
      color: #000;
      margin-bottom: 10rpx;
    }

    .local {
      font-size: 30rpx;
      color: #666;
      margin-bottom: 10rpx;
    }

    .time {
      font-size: 28rpx;
      color: #888;
    }
  }

  .borders {
    width: 100%;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .blue {
      width: 36rpx;
      height: 6rpx;
      background-color: #98c2f3;
    }
    .pink {
      width: 36rpx;
      height: 6rpx;
      background-color: #f6af99;
    }
  }
}

.desserts {
  width: 95%;
  border-radius: 20rpx;
  background-color: #fff;
  margin: 20rpx auto 0;
  .item {
    width: 100%;
    position: relative;
    padding: 10rpx;
    margin-bottom: 10rpx;

    .name {
      font-size: 32rpx;
      position: absolute;
      top: 10rpx;
      left: 170rpx;
    }

    .specs {
      font-size: 26rpx;
      color: #9d9d9d;
      position: absolute;
      top: 100rpx;
      left: 170rpx;
    }

    .price {
      color: #bc7a59;
      font-size: 30rpx;
      font-weight: bold;
      position: absolute;
      top: 60rpx;
      right: 50rpx;
    }
  }
}

.info {
  width: 95%;
  border-radius: 20rpx;
  background-color: #fff;
  padding: 20rpx 0;
  margin: 20rpx auto;

  .time {
    margin-bottom: 10rpx;
    padding: 0 5px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    text {
      font-size: 30rpx;
      color: #000;
    }

    .right {
      display: flex;
      align-items: center;
      .timeText {
        font-size: 28rpx;
        color: #666;
      }
      .jiantou {
        font-size: 30rpx;
        color: #9d9d9d;
      }
    }
  }

  .name {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10rpx;
    margin-bottom: 20rpx;
    text {
      font-size: 30rpx;
      color: #000;
    }
    input {
      width: 150px;
      height: 20rpx;
      font-size: 28rpx;
    }
  }

  .phone {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10rpx;
    margin-bottom: 20rpx;
    text {
      font-size: 30rpx;
      color: #000;
    }
    input {
      width: 150px;
      height: 20rpx;
      font-size: 28rpx;
    }
  }

  .msg {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10rpx;
    text {
      font-size: 30rpx;
      color: #000;
    }
    input {
      width: 150px;
      height: 20rpx;
      font-size: 28rpx;
    }
  }
}

.coupons {
  width: 95%;
  border-radius: 20rpx;
  background-color: #fff;
  box-sizing: border-box;
  padding: 20rpx 10rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 0 auto 20rpx;

  text {
    font-size: 30rpx;
    color: #000;
  }

  .selcou {
    display: flex;
    align-items: center;

    .couname {
      color: #f6823e;
    }

    .jiantou {
      color: #9d9d9d;
    }
  }
}

.money {
  width: 95%;
  border-radius: 20rpx;
  background-color: #fff;
  padding: 20rpx 0rpx 10rpx;
  margin: 0 auto 120rpx;

  .count {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10rpx;
    margin-bottom: 20rpx;
    .zi {
      font-size: 30rpx;
      color: #222;
    }

    .price {
      font-size: 30rpx;
      color: #000;
      font-weight: bold;
    }
  }

  .cou {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 10rpx;
    margin-bottom: 20rpx;

    .zi {
      font-size: 30rpx;
      color: #222;
    }

    .subs {
      font-size: 30rpx;
      color: #f34b4a;
      font-weight: bold;
    }
  }
}

.footer {
  width: 100%;
  padding: 10rpx 0rpx;
  border-top: 1px solid #efefef;
  background-color: #fff;
  display: block;
  position: fixed;
  bottom: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;

  .left {
    font-size: 28rpx;
    color: #000;
    margin-left: 20rpx;
    .money {
      font-size: 30rpx;
      color: #f34b4a;
      font-weight: bold;
    }
  }

  .right {
    width: 20%;
    border-radius: 100rpx;
    color: #fff;
    font-size: 28rpx;
    letter-spacing: 1rpx;
    background: linear-gradient(to right, #f6c489, #ddaa68);
    padding: 20rpx;
    text-align: center;
    margin-right: 20rpx;
  }
}
</style>
